<?php
/**
 * Artist Controller.
 *
 */
class ArtistController extends Zend_Controller_Action
{

	/**
	 * Add an artist to the database.
	 *
	 */
	public function newAction()
	{	   
	   //Add the form to the view
	   $this->view->form = $this->getAddArtistForm();

	}



    /**
     * List all the artists in the system.
     *
     */
    public function listAllArtistsAction()
    {
    }

    /**
     * Artist Items a user might be interested
     * in purchasing.
     *
     */
    public function artistaffiliatecontentAction()
    {
    }

    /**
	 * Artist Profile
	 *
	 */
	public function profileAction()
	{
	}


	/**
	 * Save the Artist entered by the user.
	 */
	 public function saveArtistAction(){
	
	  /*//Initialize variables
	  $artistName = $this->_request->getPost('artistName');
	  $genre    = $this->_request->getPost('genre');
	  $rating   = $this->_request->getPost('rating');
	  $isFav     = $this->_request->getPost('isFav');

	  //Set new escape function to use.
	  require "utils/Escape.php";
	  $escapeObj = new Escape();
	  $this->view->setEscape(array($escapeObj, "doEnhancedEscape"));

	  //Clean up inputs
	  $artistName = $this->view->escape($artistName);
	  $genre    = $this->view->escape($genre);
	  $rating   = $this->view->escape($rating);
	  $isFav     = $this->view->escape($isFav);

	  //Save the input*/
	 	
	 //Create instance of artist form
	 $form = $this->getAddArtistForm();
	 
	 if(!isset($_SESSION['id'])){
	 	$this->_forward("login");
	 }
	 //check if there were no errors
	 if($form->isValid($_POST)){
	 	//Initialize the variable
	 	$artistName = $form->getValue('artistName');
	 	$genre = $form->getValue('genre');
	 	$rating = $form->getValue('rating');
	 	$isFav = $form->getValue('isFavorite');
	 	
	 	// Set the temporary  account id  to use
	 	$userId = 10;
	 	try {
	 		// Create a db object
	 		require_once 'Db/Db_Db.php';
	 		$db = Db_Db::conn();

	 		//Initailize data to save to Db
	 		$artistData = array("artist_name"=>$artistName,
	 							"genre"=>$genre,
	 							"created_date"=>new Zend_Db_Expr("NOW()"));
	 		//Inser the artist to Db
	 		$db->insert('artists', $artistData);
	 		
	 		//Fecth the artist id
	 		$artistId = $db->lastInsertId();
	 		//Initialize data for account artist table
	 		
	 		$accountArtistData = array("account_id"=>$userId,
	 									"artist_id"=>$artistId,
	 									"rating"=>$rating,
	 									"is_fav"=>$isFav,
	 									"created_date"=>new Zend_Db_Expr("NOW()"));
	 		// Insert the data
	 		$db->insert('accounts_artists', $accountArtistData);
	 	} catch (Zend_Db_Exception $e) {
	 		//If there were errors roll everything back
	 		$db->rollBack();
	 		echo $e->getMessage();
	 	}	 	
	 }	else{
	 	$this->view->form = $form->getMessages();
	 	$this->view->form = $form;
	 }

	}
	

	/**
	 * Display news for users artist.
  	 */
	 public function newsAction()
	 {

	   //Check if the user is logged in

	   //Get the user's Id

	   //Get the artists. (Example uses static artists)
	   $artists = array("Thievery Corporation",
					   "The Eagles",
					   "Elton John");

	   //Set the view variables
	   $this->view->artists = $artists;

	   //Find the view in our new location
	   $this->view->setScriptPath("<APACHE_HOME>");
	   $this->render("news");

	 }


	/**
	 * Remove favorite artist..
	 */
	public function removeAction()
	{

	   //Check if the user is logged in

	   //Get the user's Id

	   //Get the user's artist with rating.
	   $artists = array(
	                            array( "name" => "Thievery Corporation", "rating" => 5),
	                            array("name" => "The Eagles", "rating" => 5),
	                            array("name" => "Elton John", "rating" => 4)
	                  );

	   //Create the class
	   $artistObj = new StdClass();
	   $artistObj->artists = $artists;

	   //Set the view variables
	   $this->view->assign((array)$artistObj);

	   //Set the total number of artists in the array.
	   //Demonstrates the use of a key-value array assignment.
	   $totalNumberOfArtists = array("totalArtist" => count($artists));

	   //Set the view variables
	   $this->view->assign((array)$artistObj);
	   $this->view->assign($totalNumberOfArtists);

	}


	/**
	 * Create Add Artist Form.
	 *
	 * @return Zend_Form
	 */
	private function getAddArtistForm()
	{

	    $form = new Zend_Form();
	    $form->setAction("save-artist");
	    $form->setMethod("post");
	    $form->setName("addartist");

	    //Create artist name text field.
	    $artistNameElement = new Zend_Form_Element_Text('artistName');
	    $artistNameElement->setLabel("Artist Name:");

	    //Create genres select menu
	    $genres = array("multiOptions" => array
	    (
	        "electronic"         => "Electronic",
	        "country"             => "Country",
	        "rock"                  => "Rock",
	        "r_n_b"               => "R & B",
	        "hip_hop"            => "Hip-Hop",
	        "heavy_metal"      => "Heavy-Metal",
	        "alternative_rock" => "Alternative Rock",
	        "christian"             => "Christian",
	        "jazz"                   => "Jazz",
	        "pop"                    => "Pop"
	      ));

	    $genreElement = new Zend_Form_Element_Select('genre', $genres);
	    $genreElement->setLabel("Genre:");
	    $genreElement->setRequired(true);

	    //Create favorite radio buttons.
	    $favoriteOptions = array("multiOptions" => array
	    (
	        "1" => "yes",
	        "0" => "no"
	    ));


	    $isFavoriteListElement = new Zend_Form_Element_Radio('isFavorite',
	                                             $favoriteOptions);
	    $isFavoriteListElement->setLabel("Add to Favorite List:");
	    $isFavoriteListElement->setRequired(true);

	    //Create Rating raio button
	    $ratingOptions = array("multiOptions" => array
	     (
	        "1" => "1",
	        "2" => "2",
	        "3" => "3",
	        "4" => "4",
	        "5" => "5"
	    ));

	    $ratingElement = new Zend_Form_Element_Radio('rating', $ratingOptions);
	    $ratingElement->setLabel("Rating:");
	    $ratingElement->setRequired(true)->addValidator(new Zend_Validate_Alnum(false));

	    //Create submit button
	    $submitButton = new Zend_Form_Element_Submit("submit");
	    $submitButton->setLabel("Add Artist");

	    //Add Elements to form
	    $form->addElement($artistNameElement);
	    $form->addElement($genreElement);
	    $form->addElement($isFavoriteListElement);
	    $form->addElement($ratingElement);
	    $form->addElement($submitButton);

	    return $form;

	}
	/**
	* Test - Object Oriented Select Statement
	*
	*/
	public function testoostatementAction() {
	   //Create DB object
		require_once "Db/Db_Db.php";
		$db = Db_Db::conn();
		// Create the statement
		//SELECT `artists`.`id`, `artists`.`artist_name`, `artists`.`genre`
		// Select * FROM 'artist'
		$select = new Zend_Db_Select($db);
		
		//Determine which columns to retrive
		$columns = array("artist_id" => 'id',
						"name"=>'artist_name',
						"genre"=>'genre');
		$tableInfo = array("a"=>'artists');
		$statement = $select->from($tableInfo,$columns)
						->where("artist_name=?",'Groove Armada')
						->where('genre=?','electronic')
						->orWhere('genre=?','pop');
		
		//Query the Database
		$results = $db->query($statement);
		$rows = $results->fetchAll();
		// Compare Statement
		echo $statement->__toString();
		//Supress the View
		$this->_helper->viewRenderer->setNoRender();
	}
	/**
	 * Test - Get All Fans
	 */
	public function testtoofansAction(){
		// Create Db Object
		require_once 'Db/Db_Db.php';
		$db = Db_Db::conn();
		
		// Create the statement
		//SELECT `a`.`id` AS `artist id`, `a`.`artist_name` AS `name`,
	   //`a`.`genre`,aa`.`account_id` AS `user_id`,
	   //`aa`.`created_date` AS `date_became_fan`
	   //FROM `artists` AS `a`
	   //INNER JOIN `accounts_artists` AS `aa` ON aa.artist_id = a.id 
	   $select = new Zend_Db_Select($db);
	   
	   //Determine which columns to retrive.
	   //Determine which table to retrive data from.
	   $columns = array("artist id" =>'a.id',
	   					"name" => 'a.artist_name',
	   					"genre" => 'a.genre');
	   $tableInfo = array("a" => 'artists');
	   
	    $statement = $select->from($tableInfo, $columns)
                       ->join(array("aa" => 'accounts_artists'),
                              'aa.artist_id = a.id',
                              array("user_id" => 'aa.account_id',
                                    "date_became_fan" =>
                                    'aa.created_date'))
                              ->order("date_became_fan DESC")
                              ->limit(10);
	   $results = $db->query($statement);

	   $rows = $results->fetchAll();
	   
	   //Compare Statement
	   echo $statement->__toString();
	   
	   //Supress the View
	   
	   $this->_helper->viewRenderer->setNoRender();
			   						
	}
}